<template>
  <div class="city-search">
    <div class="search-input">
      <input v-model="keyword" type="text" placeholder="请输入城市名或拼音">
    </div>
    <div class="search-content" ref="searchContent" v-show="keyword">
      <ul>
        <li class="border-bottom" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">{{ item.name }}</li>
        <li v-show="!list.length">没有找到数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll';
import { mapMutations } from 'vuex';

export default {
  name: 'city-search',
  props: {
    cities: Object
  },
  data() {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  watch: {
    keyword() {
      if(this.timer) {
        clearTimeout(this.timer);
      }
      if(!this.keyword) {
        this.list = [];
        return false;
      }
      this.timer = setTimeout(() => {
        let result = [], i;

        for(i in this.cities) {
          this.cities[i].forEach(item => {
            if(item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
              result.push(item);
            }
          });
        }

        this.list = result;
      }, 100);
    }
  },
  mounted() {
    new BScroll(this.$refs.searchContent);
  },
  methods: {
    ...mapMutations(['changeCity']),
    handleCityClick(city) {
      this.changeCity(city);
      this.$router.push('/');
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl';

.city-search
  .search-input 
    height .72rem
    padding 0 .1rem
    background $bgColor
    input 
      width 100%
      height .62rem
      padding 0 .1rem
      box-sizing border-box
      line-height .62rem
      text-align center
      border-radius .06rem
      color #666
  .search-content
    position absolute
    top 1.58rem
    left 0
    bottom 0
    right 0
    z-index 1
    overflow hidden
    background #eee
    li 
      line-height .62rem
      padding-left .2rem
      color #666 
      background #fff
</style>